﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Contour.Contrib.Controls
{
    [System.Web.UI.ValidationProperty("IsValidString")]
    public class AyahCaptchaCustomControl : WebControl, IValidator
    {   
        /// <summary>
        ///   Gets or sets the AYAH publisher key
        /// </summary>
        public string PublisherKey { get; set; }

        /// <summary>
        ///   Gets or sets the AYAH scoring key
        /// </summary>
        public string ScoringKey { get; set; }

        protected override System.Web.UI.HtmlTextWriterTag TagKey
        {
            get
            {
                return System.Web.UI.HtmlTextWriterTag.Div;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.Page.Validators.Add((IValidator)this);
        }
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Page.IsPostBack)
            {
                this.Validate();

                if (!IsValid)
                {
                    // show the captcha again, they failed.
                    // if the validation passed, we dont add the captcha again as 
                    // this visitor has already proved themselves.
                    this.AddCapthaToPage();
                }
            }
            else
            {
                this.AddCapthaToPage();
            }
        }

        /// <summary>
        ///   Adds the captcha HTML to the page.
        /// </summary>
        private void AddCapthaToPage()
        {
            var ayah = new AreYouAHuman.AyahServiceIntegration();

            var html = ayah.GetPublisherHtml(this.PublisherKey);

            this.Controls.Add(new Literal()
            {
                Text = html
            });
        }

        public string IsValidString
        {
            get
            {
                if (this.IsValid)
                {
                    return this.IsValid.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
        }

        public string ErrorMessage
        {
            get
            {
                return "Captcha verification failed";
            }
            set
            {
                ErrorMessage = value;
            }

        }

        public bool IsValid
        {
            get;
            set;
        }

        public void Validate()
        {
            var sessionSecret = this.Page.Request.Form.Get("session_secret");

            if (string.IsNullOrWhiteSpace(sessionSecret))
            {
                IsValid = false;
                throw new ApplicationException("We dont have a session secret, there is a problem");
            }
            else
            {
                var ayah = new AreYouAHuman.AyahServiceIntegration();
                var result = ayah.ScoreResult(sessionSecret, this.ScoringKey);

                IsValid = result;
            }
        }
    }
}